package com.example.libpro.MyActivity.adminActivity;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import androidx.appcompat.app.AppCompatActivity;

import com.example.libpro.R;
import com.example.libpro.Service.BookService;

public class AdminAddBookActivity extends AppCompatActivity implements View.OnClickListener {
    private static final String TAG = "AdminAddBookActivity";
    private BookService bookService;
    private boolean bookServiceBound;
    private EditText etBookName;
    private EditText etAuthor;
    private EditText etStock;
    private EditText etIntro;
    private Button btnAddBook;
    private ServiceConnection connection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName className, IBinder service) {
            BookService.LocalBinder binder = (BookService.LocalBinder) service;
            bookService = binder.getService();
            bookServiceBound = true;
        }

        @Override
        public void onServiceDisconnected(ComponentName arg0) {
            bookServiceBound = false;
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_admin_add_book);
        Log.i(TAG, "onCreate: Activity 初始化完成，开始绑定 bookService");
        Intent intent = new Intent(this, BookService.class);
        bindService(intent, connection, Context.BIND_AUTO_CREATE);
        etBookName = findViewById(R.id.etBookName);
        etAuthor = findViewById(R.id.etAuthor);
        etStock = findViewById(R.id.etStock);
        etIntro = findViewById(R.id.etIntro);
        btnAddBook = findViewById(R.id.btnAddBook);
        btnAddBook.setOnClickListener(this);

    }

    @Override
    public void onClick(View view) {
        //判断绑定状态和各个控件的输入
        boolean isOk = bookServiceBound && !etBookName.getText().toString().isEmpty() && !etAuthor.getText().toString().isEmpty() && !etStock.getText().toString().isEmpty() && !etIntro.getText().toString().isEmpty();
        if (isOk) {
            BookService.ServiceResult result = bookService.addBook(etBookName.getText().toString(), etAuthor.getText().toString(), etIntro.getText().toString(), Integer.parseInt(etStock.getText().toString()), Integer.parseInt(etStock.getText().toString()));
            if (result.isSuccess()) {
                Log.i(TAG, "onClick: 添加成功");
                finish();
            } else {
                Log.i(TAG, "onClick: 添加失败");
                Log.w(TAG, "onClick: " + result.getMessage());
            }
        }
    }
}